package com.scott.asyncweb.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 异步此场景
 * 1：不需要立即返回结果，例如 Dump数据，提交一个10G的数据，后台需要执行10秒，但是立即返回10毫秒就可以了。
 * 运行结果需要二次校验。
 */
@WebServlet(value = "/simple/async",asyncSupported = true)
public class SimpleAsyncServlet extends HttpServlet {

    private static final long serialVersionUID = 8707826687682002352L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        writer.println(Thread.currentThread().getName()+" 请求开始处理了</br>");
        //start async context
        AsyncContext asyncContext  =req.startAsync();



        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent event) throws IOException {
                writer.println(Thread.currentThread().getName()+" 异步请求完成</br>");
            }

            @Override
            public void onTimeout(AsyncEvent event) throws IOException {
                writer.println(Thread.currentThread().getName()+" 异步请求超时</br>");
            }

            @Override
            public void onError(AsyncEvent event) throws IOException {
                writer.println(Thread.currentThread().getName()+" 异步请求错误</br>");
            }

            @Override
            public void onStartAsync(AsyncEvent event) throws IOException {
                writer.println(Thread.currentThread().getName()+" 异步请求开始</br>");
            }
        });
        //同步操作
//        asyncContext.complete();

        //异步操作
        asyncContext.start(()->{
            writer.println(Thread.currentThread().getName()+" 请求执行中</br>");

        });
        asyncContext.complete();

    }
}
